package com.xiaoq.matrix.repository.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.mongodb.morphia.Datastore;
import org.mongodb.morphia.Key;
import org.mongodb.morphia.query.Query;
import org.mongodb.morphia.query.UpdateOperations;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.xiaoq.coms.util.IdGeneratorUtils;
import com.xiaoq.matrix.entity.ContentEntity;
import com.xiaoq.matrix.repository.IContentRepository;
import com.xiaoq.matrix.vo.ContentAndElementVo;
import com.xiaoq.qiniu.QiNiuSpaceEnum;
import com.xiaoq.qiniu.UploadUtil;
import com.xiaoq.vo.PagingVo;

@Repository
public class ContentRepositoryImpl implements IContentRepository {
	
	@Autowired
	private Datastore dataStore;
	
	private static final Logger LOG = LoggerFactory.getLogger(ContentRepositoryImpl.class);

	@Override
	public List<ContentEntity> findContentList(ContentAndElementVo contentAndElementVo,PagingVo pvo){
		String title = contentAndElementVo.getTitle();
		Long pubStar = contentAndElementVo.getPubStart();
		Long pubEnd = contentAndElementVo.getPubEnd();
		String shopId = contentAndElementVo.getShopId();
		String pubStatus = contentAndElementVo.getPubStatus();
		int ps = pvo.getPs();
		int pn = (pvo.getPn()-1)*ps;
		Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
		List<ContentEntity> contentList = null;
		Number total = 0;
		contentQuery.field("shopId").equal(shopId);
		if(StringUtils.isNotBlank(pubStatus)){
			contentQuery.field("pubStatus").equal(pubStatus);
		}
		if(StringUtils.isNotEmpty(title)){
			contentQuery.field("title").contains(title);
		}
		if(pubStar!=null){
			contentQuery.filter("createdAt >=", pubStar);
		}
		if(pubEnd!=null){
			contentQuery.filter("createdAt <=", pubEnd);
		}
		if(contentQuery!=null){
			total = contentQuery.count();
			if(total.longValue()!=0){
				LOG.info("pn: "+pn+"ps:"+ps);
				contentQuery.offset(pn).limit(ps);
				contentList = contentQuery.asList();
			}
		}
		pvo.setTc(total);
		return contentList;
	}

	@Override
	public boolean addContent(ContentEntity content) {
		if(content!=null){
			Key<ContentEntity> contentKey = dataStore.save(content);
			String resultId = (String) contentKey.getId();
			if(StringUtils.isNotEmpty(resultId)){
				return true;
			}
			
		}
		return false;
	}

	@Override
	public ContentEntity findContentEntity(String id) {
		ContentEntity content = dataStore.get(ContentEntity.class,id);
		if(content!=null){
			return content;
		}
		LOG.info("查询内容详细信息为空！");
		return null;
	}

	@Override
	public boolean delContent(String id) {
		if(id!=null){
			Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
			contentQuery.field(IdGeneratorUtils.IDGENERATOR).equal(id);
			dataStore.delete(contentQuery);
			return true;
		}
		
		return false;
	}

	@Override
	public boolean updateContent(ContentEntity content) {
		if (content != null) {
			String id = content.getId();
			String name = content.getName();
			String title = content.getTitle();
			String imgUrl = content.getImgUrl();
			String introduction = content.getIntroduction();
			String merchantId = content.getMerchantId();
			List<?> mediaList = content.getMediaList();
			String createdBy = content.getCreatedBy();
			String detailInfo = content.getDetailInfo();
			String pubStatus = content.getPubStatus();
			Long pubTime = content.getPubTime();
			String zoneProvince = content.getZoneProvince();
			String zoneCity = content.getZoneCity();
			String district = content.getZoneDistrict();

			if (id != null) {
				Query<ContentEntity> contentQuery = dataStore.createQuery(ContentEntity.class)
						.field(IdGeneratorUtils.IDGENERATOR).equal(id);
				UpdateOperations<ContentEntity> contentOperations = dataStore
						.createUpdateOperations(ContentEntity.class);
				if (name != null) {
					contentOperations.set("name", name);
				}
				if (title != null) {
					contentOperations.set("title", title);
				}
				if (imgUrl != null) {
					contentOperations.set("imgUrl", imgUrl);
				}
				if (introduction != null) {
					contentOperations.set("introduction", introduction);
				}
				if (merchantId != null) {
					contentOperations.set("merchantId", merchantId);
				}
				if (createdBy != null) {
					contentOperations.set("createdBy", createdBy);
				}
				if (detailInfo != null) {
					try {
						String htmlUrl = UploadUtil.stringUploadByte(detailInfo,
								QiNiuSpaceEnum.XIAOQ_MATRIX.getName().toLowerCase(),
								QiNiuSpaceEnum.XIAOQ_MATRIX.getDomain());
						contentOperations.set("staticPath", htmlUrl);
						LOG.info("生成静态页面的URL路径" + htmlUrl);
					} catch (IOException e) {
						e.printStackTrace();
					}
					contentOperations.set("detailInfo", detailInfo);
				}
				if (mediaList != null) {
					contentOperations.set("mediaList", mediaList);
				}
				if (pubStatus != null) {
					contentOperations.set("pubStatus", pubStatus);
				}
				if (pubTime != null && pubTime != 0) {
					contentOperations.set("pubTime", pubTime);
				}
				if (zoneProvince != null) {
					contentOperations.set("zoneProvince", zoneProvince);
				}
				if (zoneCity != null) {
					contentOperations.set("zoneCity", zoneCity);
				}
				if (district != null) {
					contentOperations.set("zoneDistrict", district);
				}
				contentOperations.set("updatedAt", System.currentTimeMillis());
				dataStore.update(contentQuery, contentOperations);
				return true;
			}

		}
		return false;

	}

	@Override
	public List<ContentEntity> findContentListByCity(String city,String district,PagingVo pv) {
		Integer ps = pv.getPs();
		Integer pn  = (pv.getPn()-1)*ps;
		Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
		List<ContentEntity> contentList = null;
		if(StringUtils.isNotBlank(city)){
			contentQuery.field("zoneCity").equal(city);
		}
		
		if(StringUtils.isNotBlank(district)){
			contentQuery.field("zoneDistrict").equal(district);
		}
		if(contentQuery.count()==0){
			contentQuery = dataStore.find(ContentEntity.class);
			contentQuery.field("zoneCity").equal(city);
			
		}
		if(contentQuery.count()==0){
			contentQuery = dataStore.find(ContentEntity.class);
			city="520100";
			contentQuery.field("zoneCity").equal(city);
		}
		List<String> statuses = new ArrayList<String>();
		statuses.add("1");
		statuses.add("2");
		contentQuery.filter("pubStatus in", statuses);
//		contentQuery.field("pubStatus").equal("1");
		Number total = contentQuery.count();
		LOG.info(total.toString());
		if(total.longValue()!=0){
			pv.setTc(total);
			contentQuery.order("-pubTime").offset(pn).limit(ps);
			contentList = contentQuery.asList();
		}else{
			LOG.warn("查询结果为空！");
		}
		return contentList;
	}

	@Override
	public List<ContentEntity> findContentListByCity(String city, String district, String catalogCode, PagingVo pv) {
		Integer ps = pv.getPs();
		Integer pn  = (pv.getPn()-1)*ps;
		Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
		List<ContentEntity> contentList = null;
		if(StringUtils.isNotBlank(city)){
			contentQuery.field("zoneCity").equal(city);
		}

		if(StringUtils.isNotBlank(district)){
			contentQuery.field("zoneDistrict").equal(district);
		}
		if(StringUtils.isNotBlank(catalogCode)){
			contentQuery.field("catalogCode").equal(catalogCode);
		}
		if(contentQuery.count()==0){
			contentQuery = dataStore.find(ContentEntity.class);
			contentQuery.field("zoneCity").equal(city);
			contentQuery.field("catalogCode").equal(catalogCode);

		}
		if(contentQuery.count()==0){
			contentQuery = dataStore.find(ContentEntity.class);
			city="520100";
			contentQuery.field("zoneCity").equal(city);
			contentQuery.field("catalogCode").equal(catalogCode);
		}
		List<String> statuses = new ArrayList<String>();
		statuses.add("1");
		statuses.add("2");
		contentQuery.filter("pubStatus in", statuses);
//		contentQuery.field("pubStatus").equal("1");
		Number total = contentQuery.count();
		LOG.info(total.toString());
		if(total.longValue()!=0){
			pv.setTc(total);
			contentQuery.order("-pubTime").offset(pn).limit(ps);
			contentList = contentQuery.asList();
		}else{
			LOG.warn("查询结果为空！");
		}
		return contentList;
	}

	@Override
	public List<ContentEntity> findContentListByCity(String city) {
		Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
		contentQuery.field("zoneCity").equal(city);
		List<ContentEntity> contentList = contentQuery.asList();
		return contentList;
	}

	@Override
	public List<ContentEntity> findContentListByCity4key(String city,String catalogCode,String key,PagingVo pv) {
		int ps = pv.getPs();
		int pn = (pv.getPn()-1)*ps;
		Query<ContentEntity> contentQuery = dataStore.find(ContentEntity.class);
		contentQuery.field("zoneCity").equal(city);
		if(StringUtils.isNotBlank(catalogCode)){
			contentQuery.field("catalogCode").equal(catalogCode);
		}

		if(StringUtils.isNotBlank(key)){
			contentQuery.field("title").contains(key);
		}
        Number total = contentQuery.count();
        pv.setTc(total);
		List<ContentEntity> contentList = contentQuery.offset(pn).limit(ps).asList();
		return contentList;
	}

	@Override
	public void save(ContentEntity entity) {
		dataStore.save(entity);
		
	}

	@Override
	public ContentEntity findCotentDetail(String id) {
		
		return dataStore.get(ContentEntity.class, id);
	}

	@Override
	public void updateContentStatus(String id, String pubStatus) {
		ContentEntity content = dataStore.get(ContentEntity.class, id);
		if(content!=null){
			content.setPubStatus(pubStatus);
			dataStore.save(content);
		}

		
	}

}
